package com.hk.service.impl;

import com.hk.commons.Constant;
import com.hk.commons.ConstantOrg;
import com.hk.commons.HqlFilter;
import com.hk.commons.entity.Organization;
import com.hk.commons.entity.UserChannel;
import com.hk.commons.entity.sys.SysRole;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.entity.sys.SysUserRoles;
import com.hk.commons.vo.CheckInfo;
import com.hk.dao.base.impl.BaseServiceImpl;
import com.hk.service.IOrganization;
import com.hk.service.IOrganization_New;
import com.hk.service.IUserChannel;
import com.hk.service.sys.ISysRole;
import com.hk.service.sys.ISysUser;
import com.hk.service.sys.ISysUserRoles;
import org.hibernate.internal.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrganizationImpl_New extends BaseServiceImpl<Organization> implements
        IOrganization_New {

	private Logger logger = LoggerFactory.getLogger(OrganizationImpl_New.class);

	@Autowired
	private IUserChannel userChannelService;

	@Autowired
	private ISysUser userService;

	@Autowired
	private ISysUserRoles sysUserRolesService;

	@Autowired
	private ISysRole sysRoleService;



	@Autowired
	private IOrganization orgService;


	@Override
	public Organization findById(Integer id) {

		Organization org = getById(id);
		return org;
	}

	@Override
	public Integer add(Organization model) {

		// 保存
		Integer id = save(model);

		Organization org = getById(id);

		// 加入助记码
		if (org.getParentID() != null) {
			Organization parentOr = findById(org.getParentID());
			if (parentOr != null) {
				org.setCode(parentOr.getCode() + "-" + id);
			}
		} else {
			org.setCode(id.toString());
		}

		org.setCts(System.currentTimeMillis());
		// 更新
		super.update(org);

		return id;
	}

    /**
     * 根据渠道名获取渠道名称
     * @param channel
     * @return
     */
	public String getChannelNameByChannelId(int channel){
		String channelName = "";
		try {
			UserChannel userChannel = userChannelService.findByChannelId(channel);
			channelName = userChannel.getName();
		}catch(Exception e){
			logger.info("getChannelNameByChannelId error channel={}", channel);
		}


		return channelName;
	}

	@Override
	public List<Integer> getDepLeaderChannelStrList(Long userId) {

		SysUser user = userService.findById(userId);

		if(user == null){
			return null;
		}
		List<SysUserRoles> sysUserRolesList = sysUserRolesService
				.getByUserAccount(user.getName());

		if(sysUserRolesList == null || sysUserRolesList.size() == 0){
			return null;
		}

		List<Integer> result = new ArrayList<Integer>();
		for (SysUserRoles sysUserRole : sysUserRolesList) {
			SysRole sysRole = sysRoleService.findById(sysUserRole.getRoleId());
			if(sysRole != null && sysRole.getRoleType() == 2){
				logger.info("user RoleName ={}, id ={}", sysRole.getName(), sysRole.getId());
				Integer channelId = userChannelService.getChannelIdByRoleId(sysRole.getId());
				logger.info("channelId ={}",  channelId);
				result.add(channelId);
			}
		}

		return result;
	}

	@Override
	public List<String> getTotalVirsulDutCodes(Integer orgId) {
		if(!hasVirsualDep(orgId)){
			return null;
		}

		Organization org = findById(orgId);

		String  orgCode = org.getCode();
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1 and status = 1 and orgType = 4 and code like '" + orgCode + "-%'  and parentID = " + orgId);
		List<Organization> orgList01 = findByFilter(hqlFilter);
		if(orgList01 == null || orgList01.size() == 0){
			return null;
		}
		List<String> codeList = new ArrayList<String>();
		for(Organization subOrg : orgList01){
			codeList.add(subOrg.getCode());
		}
		return codeList;
	}

	@Override
	public Organization getByFullName(String name) {
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("fullName",name);
		return getByFilter(hqlFilter);
	}



	public String getChannelNameByOrgId(int orgId) {
		Organization organization = findById(orgId);
		Integer channel = organization.getChannel();
        if(channel == null){
            logger.info("<-------------------getChannelName ERROR-------------------->");
            logger.info("getChannelName orgId is null , orgId ={}", orgId);
            return "华康财富";
		}else{
			//logger.info("getChannelName channelId ={}, orgId={}", channel, orgId);
            return getChannelNameByChannelId(channel);
        }
	}

	public Integer save(Organization model) {
		return (Integer) super.save(model);
	}


	@Override
	public Organization delete(Integer id) {
		Organization model = this.findById(id);
		model.setStatus(0);
		this.update(model);
		return model;
	}

	//create in 2016
	@Override
    public CheckInfo deleteCheck(Integer id) {
		CheckInfo checkInfo = new CheckInfo();
		checkInfo.setResult(true);

		Organization org = findById(id);

		HqlFilter hqlFilter = new HqlFilter();
		if(org.getOrgType() == 3){
			String orgCode = org.getCode();
			hqlFilter.addSql(" where 1=1 and status = 1 and code like '" + orgCode + "-%'");
			Long size = countByFilter(hqlFilter);
			logger.info("hqlfilter = " + hqlFilter.getWhereAndOrderHql() + " size ="  + size.longValue() );
			if(size.longValue() > 0){
				checkInfo.setResult(false);
				checkInfo.setResultMsg("请转移/删除下级公司/部门/职务后再删除！" );
			}
		}else if(org.getOrgType() == 4){
			hqlFilter.addEQFilter("orgId", id);
			Long size = userService.countByFilter(hqlFilter);

			if(size.longValue() > 0){
				checkInfo.setResult(false);
				checkInfo.setResultMsg("请转移/删除下级" + size.longValue() + "位人员后再删除！" );
			}
		}

		return checkInfo;
	}

	//create in 2016
	@Override
	public List<Organization> findByUser(Long userId) {
		if(userId == null){
			logger.info("userId is null will return, userId = " + userId);
			return null;
		}

		HqlFilter hqlFilter = new HqlFilter();

		SysUser user = userService.findById(userId);
		if(user.getOrgId() == null ){
			logger.info("user orgId is null will return, userId = " + userId);
			return  null;
		}
		Integer orgId = user.getOrgId();

		Organization org = findById(orgId);
		if(org == null || StringHelper.isEmpty(org.getCode())){
			logger.info("org  is null will return ");
			return null;
		}

		String orgCode =  this.getDepCodeByDuties(orgId);

		if (sysUserRolesService.isChannelRegis(userId)) {
			hqlFilter.addSql(" where 1=1 and status = 1 and code like '" + orgCode + "%'");
		}else if(sysUserRolesService.isOperationalManager(userId)){
			hqlFilter.addSql(" where 1=1 and status = 1" );
		}else{
			return null;
		}

		logger.info("hqlFilter = " + hqlFilter.getWhereAndOrderHql());


		List<Organization> orgList = this.findByFilter(hqlFilter);
		if(orgList != null){
			logger.info("orgList size  " + orgList.size());

		}else{
			logger.info("orgList size  " +  0);
			orgList = new ArrayList<Organization>();
		}
		/*
		String[] codeArray = orgCode.split("-");
		for (int i = 0; i < codeArray.length; i++) {
			Integer parentId = Integer.valueOf(codeArray[i]);
			Organization parent = getById(parentId);
			orgList.add(parent);
		}
		*/
		return orgList;
	}

	@Override
	public List<Organization> getVirsualDep(Integer orgId) {


		Organization organization = findById(orgId);

		if(organization == null || com.hk.commons.StringHelper.isEmpty(organization.getCode())){
			return null;
		}

		String  orgCode = organization.getCode();
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1 and status = 1 and orgType = 4 and code like '" + orgCode + "-%' and parentID = " + orgId);
		List<Organization> result = findByFilter(hqlFilter);
		return result;
	}

	//是否含有虚拟部门
	@Override
	public Boolean hasVirsualDep(Integer orgId) {
		Boolean result = false;
		Organization organization = findById(orgId);
		if(organization == null || com.hk.commons.StringHelper.isEmpty(organization.getCode())){
			return false;
		}

		String  orgCode = organization.getCode();
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1 and status = 1 and orgType = 3 and code like '" + orgCode + "-%'  and parentID = " + orgId);
		List<Organization> orgList01 = findByFilter(hqlFilter);

		hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1 and status = 1 and orgType = 4 and code like '" + orgCode + "-%' and parentID = " + orgId);
		List<Organization> orgList02 = findByFilter(hqlFilter);

		if(orgList01 != null && orgList01.size() > 0 && orgList02 != null && orgList02.size() > 0){
			result = true;
		}
		return result;
	}

	@Override
	public Boolean showVirsualDep(Integer orgId) {
		Boolean result = false;
		Organization organization = findById(orgId);
		if(organization == null || com.hk.commons.StringHelper.isEmpty(organization.getCode())){
			return false;
		}

		if(organization.getFlag01() == null || organization.getFlag01().equals("1") == false){
			return result;
		}
		String  orgCode = organization.getCode();
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1 and status = 1  and flag01 = 1 and orgType = 3 and code like '" + orgCode + "-%'  and parentID = " + orgId);
		List<Organization> orgShowList = findByFilter(hqlFilter);


		if(orgShowList != null && orgShowList.size() > 0){
			result = true;
		}

		return result;
	}

	//create in 2016
	public String getDepNameById(Integer id) {
		String name = "";
		Organization model = getById(id);
		String[] idsStr = model.getCode().split("-");
		for (int i = 0; i < idsStr.length; i++) {
			Integer parentId = Integer.valueOf(idsStr[i]);
			Organization parent = getById(parentId);
			if (parent.getOrgType().equals(
					Constant.ORGANIZATION_TYPE_DEPARTMENT)) {
				name = name + "-" + parent.getName();
			}
		}

		return name.substring(1, name.length());
	}

	/**
     * 获取部门的组织架构Code
     */
    private String getDepCodeByDuties(Integer orgId){
        String depCode = "";

        Organization org = findById(orgId);
        depCode = org.getCode();
        depCode= depCode.replace(orgId.toString(), "");

        logger.info("orgId ={}, depCode={}", orgId, depCode);
        return depCode;
    }

	public List<Organization> getSubOrgList(Integer orgId){
		Organization org = findById(orgId);

		if(org == null){
			return null;
		}

		String orgCode = org.getCode();

		HqlFilter hqlFilter = new HqlFilter();

		hqlFilter.addSql(" where 1=1 and code like '" + orgCode + "-%' order by code " );

		List<Organization> orgList = findByFilter(hqlFilter);

		return orgList;
	}


	public List<String> getSubOrgFullNameList(String name){
		List<String> result = new ArrayList<String>();
		String[] subNameList = name.split("-");
		for (int i = 0; i < subNameList.length; i++) {
			String subName = subNameList[0];
			for(int j= 1; j<=i; j++){
				subName += "-" + subNameList[j];
			}
			result.add(subName);
		}

		return result;
	}

	@Override
	public Organization getParBySonName(String sonName) {
		//logger.info("son name ={}", sonName);


		String[] subNameList = sonName.split("-");

		String parName = subNameList[0];
		for (int i = 1; i < subNameList.length - 1; i++) {
			parName += "-" + subNameList[i];
		}
		//logger.info("par name ={}", parName);

		Organization org  = getByFullName(parName);
		//logger.info("get by name result ={}", org);
		return org;
	}

	@Override
	public String getNameByFullName(String sonName) {

		String[] subNameList = sonName.split("-");
		String name = subNameList[subNameList.length -1];

		return name;
	}

	@Override
	public void checkOrg(String fullName) {
		Organization suerOrg =  getByFullName(fullName);
		if (suerOrg == null) {
			logger.info("check 01, org is not exist  name = " +  fullName);
			List<String> orgList = getSubOrgFullNameList(fullName);
			for(String str:orgList){
				Organization org =  getByFullName(str);
				if (org == null) {
					logger.info("org is not exit, name = " +  str);
					org = new Organization();
					org.setName( getNameByFullName(str));
					Organization par = getParBySonName(str);
					if (par != null) {
						org.setParentID(par.getId());
						org.setChannel(par.getChannel());
						org.setFullName(str);
						if(str.equals(fullName)){
							org.setOrgType(4);
						}else{
							org.setOrgType(3);
						}
						org.setFlag02(str);
						org.setFlag02(str);
						this.add(org);
						logger.info("will add into the db name  = " +  str);
					}else{
						logger.info("<---------------error------------------> orgPar is not exist name  = " +  str);
					}
				}else{
					logger.info("org is exist name = " +  str);
				}
			}

		}
	}

	@Override
	public void updateAllName(List<Organization> orgList, Long actUserId){
		for(Organization org: orgList){
			org.setFlag02(getDepNameById(org.getId()) + "-" + org.getName());
			org.setFullName(getDepNameById(org.getId()) + "-" + org.getName());
			orgService.update(org, actUserId);
		}
	}

	@Override
	public Integer getLatestWuZhu(Integer orgId) {
		Organization org = this.findById(orgId);
		if(org == null){
			return null;
		}

		String orgCode = org.getCode();

		String[] orgList = orgCode.split("-");

		for (int i = orgList.length -1; i >= 0; i--){
			Integer orgLeaderId =  Integer.valueOf(orgList[i]);
			logger.info("org orgLeaderId = {}", orgLeaderId);

			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addSql(" where 1=1 and status= 1 and parentId = " + orgLeaderId  + "  and depType =  " + ConstantOrg.ORG_TYPE_WUZHU);
			logger.info("hqlfilter = " + hqlFilter.getWhereAndOrderHql());
			Organization orgWuZhu = this.getByFilter(hqlFilter);

			if(orgWuZhu != null) {
				logger.info("wu zhu org id is not null , orgMsg ={}", orgWuZhu.toString());
				return orgWuZhu.getId();
			}
		}


		logger.info("wu zhu org id null , orgMsg ={}");
		return null;
	}

	@Override
	public List<Organization> getSubDepList(Integer orgId) {

		Organization organization = findById(orgId);

		if(organization == null || com.hk.commons.StringHelper.isEmpty(organization.getCode())){
			return null;
		}

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1 and status = 1  and parentID = " + orgId);
		List<Organization> result = findByFilter(hqlFilter);

		return result;
	}
}